<template>
  <div class="page confirm-page">
    <van-nav-bar title="确认订单" left-text="返回" left-arrow @click-left="onClickLeft" />
    <div class="container">
    <div></div>
    <van-cell
      class="address-item margin-top"
      size="large"
      icon="location-o"
      is-link
      @click="onSelect"
    >
      <div v-if="address && address.address_id > 0" class="has-address">
        <div class="address-name">{{address.recive_name}}, {{address.mobile}}</div>
        <div
          class="address-vice"
        >{{address.province}} {{address.city}} {{address.area}} {{address.address}}</div>
      </div>
      <div v-else class="no-address">请选择地址</div>
    </van-cell>

    <van-panel title="团购商城" class="margin-top">
      <van-card
        v-for="item in goods"
        :key="item.id"
        :num="1"
        :price="item.price"
        :desc="item.vice_title"
        :title="item.title"
        :thumb="item.image"
      />
    </van-panel>

    <van-cell-group class="margin-top">
      <van-cell title="邮费" :value="express.fee>0?express.fee:'免费包邮'"></van-cell>
    </van-cell-group>

    <van-radio-group class="margin-top" v-model="pay_type">
      <van-cell-group>
        <van-cell title="微信支付" clickable @click="pay_type = '0'">
          <van-radio slot="right-icon" name="0" />
        </van-cell>
        <van-cell title="佣金支付" :label="'佣金余额:'+(member.reward - member.froze_reward)/100 " clickable @click="setPaytype('2')">
          <van-radio slot="right-icon" name="2" />
        </van-cell>
      </van-cell-group>
    </van-radio-group>

    <group-rule></group-rule>
    <div class="margin-top30"></div>
    </div>

    <van-submit-bar :price="price" button-text="提交订单" @submit="onSubmit" />

    <!-- 联系人列表 -->
    <van-popup v-model="showList" position="bottom">
      <div v-if="list">
        <address-list
          :lists="list"
          :selected-id="address?address.address_id:0"
          @pick="pickAddress"
        />
        <div class="text-center" style="padding:20px 0;">
          <van-button v-if="isWechat" plain type="primary" @click="importAddress">从微信导入地址</van-button>
          <van-button v-else plain type="primary" @click="manageAddress">管理地址</van-button>
          <van-button class="margin-left" type="info" plain @click="addAddress">添加地址</van-button>
        </div>
      </div>
      <div v-else class="empty-box">
        <van-loading size="24px">加载中...</van-loading>
        <div style="margin-top:50px;"></div>
      </div>
    </van-popup>

    <van-popup v-model="showKeyboard" closeable position="bottom" :style="{ height: '80%' }">
      <div style="margin-top:50px;">
        <van-password-input
          v-model="secpassword"
          info="请输入安全密码"
          :focused="showKeyboard"
          @focus="showKeyboard = true"
        />
        <van-number-keyboard
          :show="showKeyboard"
          @input="onInput"
          @delete="onDelete"
          @blur="showKeyboard = false"
        />
      </div>
    </van-popup>
  </div>
</template>
<script >
import utils from "../../utils";
import config from "../../config";

export default {
  data() {
    return {
      goods_id: 0,
      goods: [],
      group_id: 0,
      address_id: 0,
      address: {},
      express: { title: "", fee: 0 },
      pay_type: '0',

      secpassword: "",
      showKeyboard: false,

      showList: false,
      list: null,

      isWechat: config.isWechat && config.wxid
    };
  },
  computed: {
    price() {
      let total_price = 0;
      this.goods.map(item => {
        total_price += item.price * item.count;
      });
      return Math.round(total_price * 100);
    },
    member() {
      return this.$store.state.userinfo
    }
  },
  mounted() {
    let params = this.$route.query;
    if (!this.goods_id && !params.goods_id) {
      this.$toast.fail("产品资料错误");
      this.$router.back();
    }
    this.goods_id = params.goods_id;
    if (params.address_id) {
      this.address_id = params.address_id;
    }
    if (params.group_id) {
      this.group_id = params.group_id;
    }
    this.prepare();
  },
  methods: {
    onClickLeft() {
      this.$router.back();
    },
    prepare() {
      this.$api
        .post("groupbuy_order/prepare", {
          goods: [{ id: this.goods_id, count: 1 }],
          group_id: this.group_id,
          address_id: this.address_id
        })
        .then(json => {
          this.goods = utils.fixListImage(json.data.goods);
          if (json.data.address) this.address = json.data.address;
          this.express = json.data.express;
        })
        .catch(err => {
          this.$toast.fail(err.msg || "产品资料错误");
          this.$router.back();
        });
    },
    onSelect() {
      this.showList = true;
      if (this.showList && !this.list) {
        this.loadAddress();
      }
    },
    loadAddress() {
      this.$api
        .get("member.address/index")
        .then(json => {
          this.list = json.data;
        })
        .catch(err => {
          this.$toast.fail(err.msg || "地址资料加载失败");
        });
    },
    pickAddress(address) {
      //console.log(address)
      this.showList = false;
      this.address = address;
    },
    manageAddress() {
      this.$router.push("/member/address");
    },
    addAddress() {
      this.$router.push("/member/address/detail");
    },
    importAddress() {
      this.$api.wechatReady(wx => {
        wx.openAddress({
          success: res => {
            var address = {};
            address.recive_name = res.userName;
            //address.recive_name = res.postalCode
            address.province = res.provinceName;
            address.city = res.cityName;
            address.area = res.countyName;
            address.address = res.detailInfo;
            //address.recive_name = res.nationalCode
            address.mobile = res.telNumber;
            //address.id = 0

            this.$api
              .post("member.address/save", { address: address, id: 0 })
              .then(json => {
                if (json.code == 1) {
                  this.$toast.success("保存成功");
                  this.loadAddress();
                }
              })
              .catch(error => {
                this.$toast.fail(error.msg || "保存失败");
              });
          }
        });
      });
    },
    setPaytype(type) {
      if(type == '2'){
        if(!this.member.has_secpassword){
          this.$dialog.confirm({
            message:'您还未设置安全密码\n是否现在去设置'
          }).then(()=>{
            this.$router.push('/member/sec_password')
          }).catch(()=>{
            
          });
          return;
        }
        if(this.member.reward - this.member.froze_reward < this.price){
          this.$toast.fail("佣金不足");
          return;
        }
      }
      this.pay_type = type
    },
    onSubmit() {
      if (!this.address || !this.address.address_id) {
        this.$toast.fail("请选择收货地址");
        return;
      }
      this.$dialog
        .confirm({
          title: this.group_id > 0 ? "确认参团" : "确认开团",
          message:
            this.group_id > 0
              ? "确认参与此团购? 拼团成功后随机抽取一名获奖者发送奖品,其它参与者退还本金,并发放佣金"
              : "开团成功后请尽快召集小伙伴们来参团, 拼团失败将不发放任何奖励,退还本金"
        })
        .then(() => {
          if (this.pay_type == '2') {
            this.showKeyboard = true;
          } else {
            this.doSubmit();
          }
        });
    },
    onInput(key) {
      this.secpassword = (this.secpassword + key).slice(0, 6);
      if (this.secpassword.length >= 6) {
        this.doSubmit();
      }
    },
    onDelete() {
      this.secpassword = this.secpassword.slice(0, this.secpassword.length - 1);
    },
    doSubmit() {
      this.$toast.loading();
      this.$api
        .post("groupbuy_order/confirm", {
          goods: [{ id: this.goods_id, count: 1 }],
          group_id: this.group_id,
          address_id: this.address.address_id,
          total_price: this.price / 100,
          secpassword: this.secpassword,
          pay_type: this.pay_type,
          openid: this.$api.openid
        })
        .then(json => {
          if (json.code == 1) {
            let order_id = json.data.order_id;
            if(!order_id){
              this.$toast.fail('下单失败')
              return;
            }
            this.$toast.success(json.msg);
            if(json.data.payed){
              this.$router.replace("/group/order/" + order_id);
              return;
            }
            this.$api.wxPay(order_id,'GB').then(()=>{
              if (this.group_id) {
                order_id = this.group_id;
              }
              this.$router.replace("/group/order/" + order_id);
            }).catch(()=>{
              this.$router.replace(
                "/member/groupbuy_order/detail?id=" + order_id
              );
            })
          }
        })
        .catch(err => {
          this.$toast.fail(err.msg || "下单失败");
        });
    }
  }
};
</script>
<style lang="scss">
.confirm-page {
  .address-item {
    .has-address {
      padding: 5px;
    }
    .no-address {
      line-height: 3em;
      color: #999;
    }
  }
  .van-card {
    background: #fff;
  }
}
</style>